import * as vscode from 'vscode';
import axios from 'axios';
import { DifyService } from './difyService';
import { GitScmEnhancer } from './gitScmEnhancer';
import { ScmInterceptor } from './scmInterceptor';
import { ConfigService, RemoteConfig } from './configService';
import { AuthService,isLoggedIn } from './authService';
import { MyFlatListViewProvider } from './myFlatListView';
import { Logger } from './logger';
import { getUserMap, getCurrentUserId } from './userUtil';
import { maskApiKey } from './configService';
import { buildProjectIndex } from './projectIndexer';
import { ProjectInfoService } from './projectInfoService';

let difyService: DifyService;
let gitScmEnhancer: GitScmEnhancer;
let scmInterceptor: ScmInterceptor;
let authService: AuthService;
let projectInfoService: ProjectInfoService;
let statusBar: vscode.StatusBarItem;
let taskRefreshTimer: NodeJS.Timeout | undefined;



let globalContext: vscode.ExtensionContext | undefined;

// 状态ID枚举
enum StatusIdEnum {
  NOT_STARTED = '43030321',
  IN_PROGRESS = '43030326',
  FINISHED = '43030330',
}

/** 用户映射表接口 */
const USER_MAP_URL = 'https://test-jobs.cyouops.com/config_center/api/v1/configs/demo/code.review/';
// 用户映射表缓存键
const USER_MAP_KEY = 'userMapCache';
//用户映射表本地缓存过期时间（1小时）
const USER_MAP_EXPIRE_MS = 60 * 60 * 1000;
/** 自定义字段ID（例：补充字段） */
const CUSTOM_FIELD_ID = '40791765';
/** 进行中任务默认工时 */
const DEFAULT_WORKING_HOURS = '5.0';

/** coding.net OpenAPI 基础地址 */
const CODING_API_BASE = 'https://e.coding.net/open-api/';
/** 修改任务状态接口 */
const CODING_MODIFY_ISSUE_URL = `${CODING_API_BASE}?action=ModifyIssue`;
/** 拉取任务列表接口 */
const CODING_ISSUE_LIST_URL = `${CODING_API_BASE}?Action=DescribeIssueList&action=DescribeIssueList`;
/** 拉取任务最大数量 */
const TASK_FETCH_LIMIT = 100;
/** 任务自动刷新间隔（毫秒，20分钟） */
const TASK_AUTO_REFRESH_INTERVAL = 20 * 60 * 1000;

// 1. 定义 Task 类型接口
interface Task {
  id: number;
  title: string;
  assigneeId?: number;
  statusId: string;
  statusName: string;
  description?: string;
  type: string;
  mappedStatus?: string;
}

interface IssueStatusUpdatePayload {
  IssueCode: number;
  ProjectName: string;
  StatusId: string;
  CustomFieldValues?: Array<{ Content: string; Id: string }>;
  WorkingHours?: string;
}
// 2. 工具函数
function getLocalTaskList(context: vscode.ExtensionContext): Task[] {
  const projectName = context.globalState.get('codingProjectName', '');
  if (projectName) {
    const cacheKey = `taskList_${projectName}`;
    const cached = context.globalState.get<Task[]>(cacheKey, []);
    console.log('[getLocalTaskList] 读取缓存:', cacheKey, cached);
    // 打印所有 SUB_TASK
    console.log('[getLocalTaskList] 当前 SUB_TASK:', Array.isArray(cached) ? cached.filter(t => t.type === 'SUB_TASK') : []);
    if (Array.isArray(cached) && cached.length > 0) {
      return cached;
    }
  }
  return [];
}

export async function activate(context: vscode.ExtensionContext) {
    globalContext = context;
    console.log('Dify Code Review extension is now active!');

    ConfigService.initialize(context);

    // 任务数据源始终从本地存储读取
     MyFlatListViewProvider.setTaskSource(() =>
       getLocalTaskList(context!)
     );

    // Initialize AuthService
    authService = new AuthService(context);

    // Initialize ProjectInfoService
    projectInfoService = new ProjectInfoService(context, authService);

    // 用默认配置初始化
    const defaultConfig: RemoteConfig = {
        apiKey: '',
        apiEndpoint: '',
        langChainEndpoint: 'https://langchain.cyouai.com/v1/aggregate-commit',
        maxDiffLength: 1000,
        timeout: 10000
    };
    difyService = new DifyService(defaultConfig, authService);
    gitScmEnhancer = new GitScmEnhancer(difyService);
    scmInterceptor = new ScmInterceptor(difyService, defaultConfig, authService);

      // 判断是否已登录，完成自动拉取任务
     const isLogin = await isLoggedIn(context);
     if (isLogin) {
        await fetchAndStoreTasks(context);
        MyFlatListViewProvider.refreshAll();
      }


    // vscode.window.withProgress(
    //   {
    //     location: vscode.ProgressLocation.Notification,
    //     title: '正在构建项目全局索引...'
    //   },
    //   async (progress) => {
    //     await buildProjectIndex(process.cwd(), progress);
    //     vscode.window.showInformationMessage('项目全局索引构建完成！');
    //   }
    // );

    // Initialize Git SCM enhancer
    gitScmEnhancer.initialize();
    // Initialize SCM interceptor
    scmInterceptor.initialize();

    // 启动项目信息自动更新服务
    projectInfoService.startAutoUpdate();

    // 注册自定义平铺列表面板
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider(
            MyFlatListViewProvider.viewType,
            new MyFlatListViewProvider(context)
        )
    );

    // 封装修改任务状态的请求
    async function modifyIssueStatus({
      taskId,
      statusId,
      workingHours,
      recordHour
    }: {
      taskId: number,
      statusId: string,
      workingHours?: string,
      recordHour?: any
    }) {
      function pad(n: number) { return n < 10 ? '0' + n : n; }
      const now = new Date();
      const dateStr = now.getFullYear() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate()) + ' '
        + pad(now.getHours()) + ':' + pad(now.getMinutes()) + ':' + pad(now.getSeconds());
      const apiKey = context.globalState.get('codingApiKey', '');
      const projectName = context.globalState.get('codingProjectName', '');
      if (!apiKey || !projectName) {
        vscode.window.showWarningMessage('请先在侧边栏设置 API Key 和项目');
        return;
      }
      let payload: any = {
        IssueCode: taskId,
        ProjectName: projectName,
        StatusId: statusId
      };
      if (statusId === StatusIdEnum.IN_PROGRESS) {
        payload.CustomFieldValues = [
          { Content: dateStr, Id: CUSTOM_FIELD_ID }
        ];
        payload.WorkingHours = workingHours || DEFAULT_WORKING_HOURS;
      }
      if (statusId === StatusIdEnum.FINISHED && recordHour) {
        payload.RecordHour = recordHour;
      }
      try {
        await axios.post(CODING_MODIFY_ISSUE_URL, payload, {
          headers: {
            Authorization: `token ${apiKey}`,
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Host': 'e.coding.net',
            'Connection': 'keep-alive'
          },
          timeout: 5000
        });
      } catch (err) {
        console.error('[后端] modifyIssueStatus 请求失败', err);
        throw err;
      }
    }

    // 注册命令：设置 API Key
    context.subscriptions.push(
      vscode.commands.registerCommand('dify-code-review.setApiKey', async () => {
        const apiKey = await vscode.window.showInputBox({
          prompt: '请输入你的 CODING 平台 API Key',
          ignoreFocusOut: true,
          password: true,
          placeHolder: 'API Key'
        });
        if (apiKey) {
          const cleanApiKey = apiKey.replace(/\s+/g, '');
          await context.globalState.update('codingApiKey', cleanApiKey);
          // 清空所有分项目缓存、任务缓存、项目名和用户信息
          const allKeys = context.globalState.keys();
          for (const key of allKeys) {
            if (
              key.startsWith('taskList_') ||
              key === 'taskList' ||
              key === 'codingProjectName'
            ) {
              await context.globalState.update(key, []);
            }
          }
          MyFlatListViewProvider.refreshAll();
          // 主动推送空项目、空任务，确保前端 UI 立即同步
          if (MyFlatListViewProvider._currentInstance && MyFlatListViewProvider._currentInstance._view) {
            MyFlatListViewProvider._currentInstance._view.webview.postMessage({
              command: 'setProjects',
              projects: [],
              projectName: ''
            });
            MyFlatListViewProvider._currentInstance._view.webview.postMessage({
              command: 'setProjectName',
              projectName: ''
            });
            MyFlatListViewProvider._currentInstance._view.webview.postMessage({
              command: 'setTasks',
              tasks: []
            });
          }
          vscode.window.showInformationMessage('API Key 已保存');

          try {
            const userId = await getCurrentUserId(context, authService);
            // 动态import避免循环依赖
            const { fetchCodingProjects } = await import('./myFlatListView');
            const projects = await fetchCodingProjects(cleanApiKey, userId);
            if (projects && projects.length > 0) {
              vscode.window.showInformationMessage(`已自动拉取项目列表，共${projects.length}个项目`);
              // 主动推送项目列表到Webview
              if (MyFlatListViewProvider._currentInstance && MyFlatListViewProvider._currentInstance._view) {
                MyFlatListViewProvider._currentInstance._view.webview.postMessage({
                  command: 'setProjects',
                  projects,
                  projectName: context.globalState.get('codingProjectName', '')
                });
              }
            } else {
              vscode.window.showWarningMessage('API Key 已保存，但未能拉取到项目列表');
            }
          } catch (e: any) {
            vscode.window.showErrorMessage('API Key 已保存，但拉取项目列表失败: ' + (e.message || e.toString()));
          }
        }
      })
    );


    // 注册命令：将未开始任务设为进行中
    context.subscriptions.push(
      vscode.commands.registerCommand('myFlatListView.markTaskInProgress', async (taskId: number) => {
        if (!(await isLoggedIn(context))) {
          vscode.window.showWarningMessage('请先登录再刷新任务列表');
          await context.globalState.update('taskList', []);
          MyFlatListViewProvider.refreshAll();
          return;
        }
        // 操作前强制拉取最新任务
        await fetchAndStoreTasks(context);
        const taskList = getLocalTaskList(context);
        const projectName = context.globalState.get('codingProjectName', '');
        console.log('[后端] markTaskInProgress 当前项目:', projectName, '任务ID:', taskId, '本地任务列表:', taskList);
        // 打印所有 SUB_TASK
        console.log('[后端] 当前所有 SUB_TASK:', taskList.filter(t => t.type === 'SUB_TASK'));
        if (!taskList || taskList.length === 0) {
          vscode.window.showWarningMessage('任务正在刷新，请稍后再试');
          console.log('[后端] markTaskInProgress 操作时本地任务列表为空，可能正在刷新', '当前项目:', projectName, '任务ID:', taskId);
          return;
        }
        const task = taskList.find(t => Number(t.id) === Number(taskId));
        if (!task) {
          vscode.window.showWarningMessage('未找到该任务，可能已过期或被删除，请刷新后重试');
          console.log('[后端] markTaskInProgress 未找到 task, id:', taskId, '当前项目:', projectName, '本地任务列表:', taskList);
          return;
        }
        try {
          await modifyIssueStatus({ taskId, statusId: StatusIdEnum.IN_PROGRESS, workingHours: DEFAULT_WORKING_HOURS });
          vscode.window.showInformationMessage(`"${task.title}" 已设为进行中（远程）`);
          // 延迟拉取，便于观察后端延迟
          await new Promise(r => setTimeout(r, 1500));
          await fetchAndStoreTasks(context);
          const refreshedList = getLocalTaskList(context);
          console.log('[后端] 状态变更后最新 SUB_TASK:', refreshedList.filter(t => t.type === 'SUB_TASK'));
          MyFlatListViewProvider.refreshAll();
        } catch (e: any) {
          vscode.window.showErrorMessage('设置任务状态失败: ' + (e.message || e.toString()));
          console.error('[后端] modifyIssueStatus 请求失败', e);
        }
      })
    );

    // 注册命令：关闭任务（×按钮）
    context.subscriptions.push(
      vscode.commands.registerCommand('myFlatListView.closeTask', async (taskId: number) => {
        if (!(await isLoggedIn(context))) {
          vscode.window.showWarningMessage('请先登录再刷新任务列表');
          await context.globalState.update('taskList', []);
          MyFlatListViewProvider.refreshAll();
          return;
        }
        // 操作前强制拉取最新任务
        await fetchAndStoreTasks(context);
        const taskList = getLocalTaskList(context);
        const projectName = context.globalState.get('codingProjectName', '');
        console.log('[后端] closeTask 当前项目:', projectName, '任务ID:', taskId, '本地任务列表:', taskList);
        if (!taskList || taskList.length === 0) {
          vscode.window.showWarningMessage('任务正在刷新，请稍后再试');
          console.log('[后端] closeTask 操作时本地任务列表为空，可能正在刷新', '当前项目:', projectName, '任务ID:', taskId);
          return;
        }
        const task = taskList.find(t => Number(t.id) === Number(taskId));
        if (!task) {
          vscode.window.showWarningMessage('未找到该任务，可能已过期或被删除，请刷新后重试');
          console.log('[后端] closeTask 未找到 task, id:', taskId, '当前项目:', projectName, '本地任务列表:', taskList);
          return;
        }
        try {
          await modifyIssueStatus({ taskId, statusId: StatusIdEnum.NOT_STARTED });
          vscode.window.showInformationMessage(`"${task.title}" 已关闭（远程）`);
          await fetchAndStoreTasks(context);
          MyFlatListViewProvider.refreshAll();
        } catch (e: any) {
          vscode.window.showErrorMessage('关闭任务失败: ' + (e.message || e.toString()));
          console.error('[后端] modifyIssueStatus 请求失败', e);
        }
      })
    );

    // 注册命令：标记任务为已完成
    context.subscriptions.push(
      vscode.commands.registerCommand('myFlatListView.markDone', async (taskId: number) => {
        // 操作前强制拉取最新任务
        await fetchAndStoreTasks(context);
        const taskList = getLocalTaskList(context);
        const projectName = context.globalState.get('codingProjectName', '');
        console.log('[后端] markDone 当前项目:', projectName, '任务ID:', taskId, '本地任务列表:', taskList);
        if (!taskList || taskList.length === 0) {
          vscode.window.showWarningMessage('任务正在刷新，请稍后再试');
          console.log('[后端] markDone 操作时本地任务列表为空，可能正在刷新', '当前项目:', projectName, '任务ID:', taskId);
          return;
        }
        const task = taskList.find(t => Number(t.id) === Number(taskId));
        if (!task) {
          vscode.window.showWarningMessage('未找到该任务，可能已过期或被删除，请刷新后重试');
          console.log('[后端] markDone 未找到 task, id:', taskId, '当前项目:', projectName, '本地任务列表:', taskList);
          return;
        }
        try {
          // 无论原状态，标记为已完成都带 RecordHour
          await modifyIssueStatus({
            taskId: Number(taskId),
            statusId: StatusIdEnum.FINISHED,
            recordHour: {
              remainingHour: DEFAULT_WORKING_HOURS,
              spendHour: DEFAULT_WORKING_HOURS,
              StartAt: Date.now(),
              WorkingDesc: ''
            }
          });
          vscode.window.showInformationMessage(`"${task.title}" 已标记为已完成（远程）`);
          await fetchAndStoreTasks(context);
          MyFlatListViewProvider.refreshAll();
        } catch (e: any) {
          vscode.window.showErrorMessage('标记为已完成失败: ' + (e.message || e.toString()));
          console.error('[后端] modifyIssueStatus 请求失败', e);
        }
      })
    );

    // 编辑器输入@时弹出未开始任务的下拉补全建议（仅@@时才有内容）
    context.subscriptions.push(
      vscode.languages.registerCompletionItemProvider(
        { scheme: 'file', language: '*' },
        {
          provideCompletionItems(document, position) {
            const line = document.lineAt(position).text;
            const prefix = line.slice(0, position.character);
            // 只要有@就触发
            const atMatch = prefix.match(/@([\u4e00-\u9fa5\w]*)$/);
            if (!atMatch) {
              return undefined;
            }
            // 但只有@@才返回补全项
            if (!prefix.endsWith('@@') && !prefix.match(/@@([\u4e00-\u9fa5\w]*)$/)) {
              return undefined;
            }
            const query = prefix.match(/@@([\u4e00-\u9fa5\w]*)$/)?.[1] || '';
            // 直接从本地存储获取所有需求/缺陷
            const all = getLocalTaskList(context);
            console.log('@@补全触发', { line, prefix, query, candidatesCount: all.length, all });
            if (!all || all.length === 0) {
              vscode.window.showInformationMessage('本地任务列表为空，正在尝试自动刷新，请稍后再试。');
              fetchAndStoreTasks(context);
              return undefined;
            }
            const candidates = all.filter(item => {
              if (item.type === 'REQUIREMENT' && item.statusName === '未开始') return item.title.includes(query);
              if (item.type === 'DEFECT' &&  item.statusName === '未开始' ) return item.title.includes(query);
              if (item.type === 'SUB_TASK' && item.statusName === '未开始') return item.title.includes(query);
              return false;
            });
            if (candidates.length === 0) return undefined;
            return candidates.map(t => {
              const item = new vscode.CompletionItem(t.title, vscode.CompletionItemKind.Value);
              item.detail = '可选择激活';
              item.documentation = t.description || t.description;
              item.sortText = '000' + t.title; // 排在最前
              item.command = {
                command: 'myFlatListView.markTaskInProgress',
                title: '设为进行中',
                arguments: [t.id]
              };
              // 只插入 #id 标题，不设置 range
              item.insertText = `#${t.id} ${t.title}`;
              return item;
            });
          }
        },
        '@' // 触发字符
      )
    );

    // 注册手动刷新配置命令
    const refreshConfigCmd = vscode.commands.registerCommand('dify-code-review.refreshConfig', async () => {
        try {
            const config = await ConfigService.refreshConfig();
            await getUserMap(globalContext!, true); // 强制刷新用户映射表
            difyService.updateConfig(config);
            vscode.window.showInformationMessage('远程配置和用户映射表刷新成功！');
        } catch (e) {
            vscode.window.showErrorMessage('远程配置刷新失败: ' + (e instanceof Error ? e.message : e));
        }
    });
    context.subscriptions.push(refreshConfigCmd);

    // 注册登录命令，登录成功后自动拉取任务
    const loginCmd = vscode.commands.registerCommand('dify-code-review.login', async () => {
        try {
            const user = await authService.login();
            vscode.window.showInformationMessage(`登录成功，欢迎 ${user.name}`);
            updateStatusBar();
            await fetchAndStoreTasks(context);
            MyFlatListViewProvider.refreshAll();
            startTaskAutoRefresh(context);
        } catch (e: any) {
            vscode.window.showErrorMessage('登录失败: ' + e.message);
        }
    });
    context.subscriptions.push(loginCmd);

    // 注册登出命令，登出后清空任务
    const logoutCmd = vscode.commands.registerCommand('dify-code-review.logout', async () => {
        await authService.logout();
        vscode.window.showInformationMessage('已登出');
        updateStatusBar();
        await context.globalState.update('taskList', []);
        MyFlatListViewProvider.refreshAll();
        MyFlatListViewProvider.clearTasks();
        vscode.window.showInformationMessage('已登出，任务列表已清空');
        stopTaskAutoRefresh();
    });
    context.subscriptions.push(logoutCmd);

    // 登录后自动拉取任务（如果已登录）
    const user = await authService.getCurrentUser();
    updateStatusBar();


    // 状态栏显示当前用户
    statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBar.command = 'dify-code-review.login';
    context.subscriptions.push(statusBar);

    // 注册手动刷新任务命令，供侧边栏刷新按钮调用
    context.subscriptions.push(
      vscode.commands.registerCommand('taskList.manualRefresh', async () => {
        // vscode.window.showInformationMessage('[日志] taskList.manualRefresh 被调用');
        console.log('[日志] taskList.manualRefresh 被调用');
        await fetchAndStoreTasks(context);
        // vscode.window.showInformationMessage('[日志] MyFlatListViewProvider.refreshAll 被调用');
        console.log('[日志] MyFlatListViewProvider.refreshAll 被调用');
        MyFlatListViewProvider.refreshAll();
        // 新增：自动触发补全
        await vscode.commands.executeCommand('editor.action.triggerSuggest');
      })
    );

    async function updateStatusBar() {
        const user = await authService.getCurrentUser();
        if (user) {
            statusBar.text = `$(account) ${user.name}`;
            statusBar.tooltip = '点击切换用户';
            statusBar.command = 'dify-code-review.logout';
        } else {
            statusBar.text = '$(account) 登录';
            statusBar.tooltip = '点击登录';
            statusBar.command = 'dify-code-review.login';
        }
        statusBar.show();
    }

    updateStatusBar();
}

// 拉取任务并存入本地
async function fetchAndStoreTasks(context: vscode.ExtensionContext) {
  const logger = Logger.getInstance();
  logger.info('[fetchAndStoreTasks] 开始拉取任务');
  // vscode.window.showInformationMessage('[fetchAndStoreTasks] 开始拉取任务');
  if (!(await isLoggedIn(context))) {
    logger.info('[fetchAndStoreTasks] 未登录，清空任务列表');
    vscode.window.showWarningMessage('请先登录再刷新任务列表');
    await context.globalState.update('taskList', []);
    MyFlatListViewProvider.refreshAll();
    return;
  }
  const apiKey = context.globalState.get('codingApiKey', '');
  const projectName = context.globalState.get('codingProjectName', '');
  logger.info(`[fetchAndStoreTasks] 当前API Key: ${maskApiKey(apiKey)}, 当前项目: ${projectName}`);
  // vscode.window.showInformationMessage(`[fetchAndStoreTasks] 当前API Key: ${maskApiKey(apiKey)}, 当前项目: ${projectName}`);
  if (!apiKey || !projectName) {
    vscode.window.showWarningMessage('请先在侧边栏设置 API Key 和项目');
    await context.globalState.update('taskList', []);
    MyFlatListViewProvider.refreshAll();
    return;
  }

  // 1. 获取用户映射表 peopleArr
  let userId: number | undefined;
  try {
    userId = await getCurrentUserId(context, authService);
    logger.info(`[fetchAndStoreTasks] 匹配到的 userId: ${userId}`);
  } catch (e: any) {
    logger.error('[fetchAndStoreTasks] 获取用户映射表或解析失败', e);
    vscode.window.showErrorMessage('获取用户映射表失败: ' + (e.message || e.toString()));
    await context.globalState.update('taskList', []);
    MyFlatListViewProvider.refreshAll();
    return;
  }

  // 4. 拉取任务
  const url = CODING_ISSUE_LIST_URL;
  const headers = {
    'Authorization': `token ${apiKey}`,
    'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
    'Content-Type': 'application/json',
    'Accept': '*/*',
    'Host': 'e.coding.net',
    'Connection': 'keep-alive'
  };
  const data = {
    "ProjectName": projectName,
    "IssueType": "ALL",
    "Offset": "0",
    "Limit": String(TASK_FETCH_LIMIT),
    "Conditions": [
      { "Key": "ASSIGNEE", "Value": String(userId) },
      { "Key": "STATUS_TYPE", "Value": "TODO,PROCESSING,COMPLETED" }
    ],
    "SortKey": "CODE",
    "SortValue": "DESC"
  };
  logger.info(`[fetchAndStoreTasks] 拉取任务参数: ${JSON.stringify(data)}`);
  try {
    const resp = await axios.post(url, data, { headers });
    logger.info('[fetchAndStoreTasks] axios.post 返回: ' + JSON.stringify(resp.data));
    // 新增：打印接口原始响应
    console.log('[fetchAndStoreTasks] 接口原始响应:', JSON.stringify(resp.data, null, 2));
    // vscode.window.showInformationMessage('[fetchAndStoreTasks] axios.post 返回: ' + JSON.stringify(resp.data));
    // 检查是否有权限错误
    if (resp.data && resp.data.Response && resp.data.Response.Error) {
      const code = resp.data.Response.Error.Code;
      if(code === 'UnauthorizedOperation' ){
        vscode.window.showErrorMessage('无本项目权限，请检查 API Key 是否有该项目权限');
      }else{
        vscode.window.showErrorMessage(`任务接口异常: [${code}] ${resp.data.Response.Error.Message || ''}`);
      }

      await context.globalState.update('taskList', []);
      const cacheKey = `taskList_${projectName}`;
      await context.globalState.update(cacheKey, []);
      MyFlatListViewProvider.refreshAll();
      return;
    }
    logger.info(`[fetchAndStoreTasks] 拉取任务接口返回: ${JSON.stringify(resp.data)}`);
    const list = resp.data.Response.IssueList || [];
    // 打印所有 SUB_TASK
    console.log('[fetchAndStoreTasks] 拉取到的 SUB_TASK:', list.filter((item: any) => item.Type === 'SUB_TASK'));
    logger.info(`[fetchAndStoreTasks] 拉取到任务数量: ${list.length}`);
    // vscode.window.showInformationMessage(`[fetchAndStoreTasks] 拉取到任务数量: ${list.length}`);
    // 只保留最后一层结点
    const leafTasks = list.filter((item: any) => !list.some((child: any) => child.ParentId === item.Id));
    // 只保留需求和缺陷，过滤掉任务，并只保留未开始和进行中的数据
    const statusMap = {
      REQUIREMENT: {
        '未开始': '未完成',
        '需求确认': '进行中',
        '测试中': '进行中',
        '进行中': '进行中',
        '待验证': '进行中',
        '已完成': '已完成',
        '已关闭': '已完成',
        '已结束': '已完成',
      },
      DEFECT: {
        '未开始': '未完成',
        '测试中': '进行中',
        '待验证': '进行中',
        '进行中': '进行中',
        '已完成': '已完成',
        '拒绝': '已完成',
        '已结束': '已完成',
      },
      SUB_TASK: {
        '未开始': '未完成',
        '需求确认': '进行中',
        '测试中': '进行中',
        '进行中': '进行中',
        '待验证': '进行中',
        '已完成': '已完成',
        '已关闭': '已完成',
        '已结束': '已完成',
      }
    };

    const tasks = leafTasks
      .filter((item: any) => (item.Type === 'REQUIREMENT' || item.Type === 'DEFECT' || item.Type === 'SUB_TASK'))
      .map((item: any) => {
        const mappedStatus = statusMap[item.Type as keyof typeof statusMap]?.[item.IssueStatusName as keyof (typeof statusMap)[keyof typeof statusMap]] || '未完成';
        return {
          id: item.Code,
          title: item.Name,
          assigneeId: item.AssigneeId,
          statusId: item.IssueStatusId,
          statusName: item.IssueStatusName,
          description: item.Description,
          type: item.Type,
          mappedStatus
        };
      })
      .filter((item: any) => item.mappedStatus === '未完成' || item.mappedStatus === '进行中');
    // 打印最终 tasks 里的 SUB_TASK
    console.log('[fetchAndStoreTasks] 最终 tasks 里的 SUB_TASK:', tasks.filter((t: any) => t.type === 'SUB_TASK'));
    logger.info(`[fetchAndStoreTasks] 过滤后任务数量: ${tasks.length}`);
    // vscode.window.showInformationMessage(`[fetchAndStoreTasks] 过滤后任务数量: ${tasks.length}`);
    await context.globalState.update('taskList', tasks);
    // 强制覆盖本地缓存
    const cacheKey = `taskList_${projectName}`;
    await context.globalState.update(cacheKey, tasks);
    console.log('[fetchAndStoreTasks] 已写入缓存:', cacheKey, tasks);
    if (tasks.length === 0) {
      vscode.window.showWarningMessage('当前项目暂无任务项！');
    } else {
      vscode.window.showInformationMessage(`已同步任务 ${tasks.length} 条`);
    }
  } catch (e: any) {
    logger.error('[fetchAndStoreTasks] 拉取任务接口失败', e);
    vscode.window.showErrorMessage('任务同步失败: ' + (e.message || e.toString()));
  }
}

function startTaskAutoRefresh(context: vscode.ExtensionContext) {
  stopTaskAutoRefresh();
  taskRefreshTimer = setInterval(() => {
    fetchAndStoreTasks(context).then(() => MyFlatListViewProvider.refreshAll());
  }, TASK_AUTO_REFRESH_INTERVAL); // 20分钟
}
function stopTaskAutoRefresh() {
  if (taskRefreshTimer) {
    clearInterval(taskRefreshTimer);
    taskRefreshTimer = undefined;
  }
}

export function deactivate() {
    if (gitScmEnhancer) {
        gitScmEnhancer.dispose();
    }
    if (scmInterceptor) {
        scmInterceptor.dispose();
    }
    if (projectInfoService) {
        projectInfoService.stopAutoUpdate();
    }
} 